package com.small.common.base;

import com.small.common.base.service.BaseService;
import com.small.common.msg.Msg;
import com.small.common.msg.MsgCommon;
import com.small.common.msg.MsgData;
import com.small.common.msg.MsgPage;
import com.small.common.util.Query;
import com.small.common.util.val.group.ValAdd;
import com.small.common.util.val.group.ValUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 通用controller实现
 *
 * @param <Service> service 接口
 * @param <Entity>  实体
 */
public class BaseController<Service extends BaseService, Entity> {

    @Autowired
    protected Service service;

    @PostMapping
    public Msg add(@Validated(ValAdd.class) @RequestBody Entity entity) {
        service.insertSelective(entity);
        return MsgCommon.SUCCESS;
    }

    @DeleteMapping("{id}")
    public Msg delete(@PathVariable(name = "id") Long id) {
        service.deleteById(id);
        return MsgCommon.SUCCESS;
    }

    @PutMapping
    public Msg update(@Validated(ValUpdate.class) @RequestBody Entity entity) {
        service.updateSelectiveById(entity);
        return MsgCommon.SUCCESS;
    }

    @GetMapping("{id}")
    public MsgData<Entity> get(@PathVariable(name = "id") Long id) {
        return new MsgData(service.selectById(id));
    }

    @GetMapping("all")
    public MsgData<List<Entity>> all() {
        return new MsgData<>(service.selectListAll());
    }

    @GetMapping("page")
    public MsgPage<Entity> page(@RequestParam(required = false) Map<String, Object> params) {
        return service.selectByQuery(new Query(params));
    }
}
